import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import {
  Card,
  CardHeader,
  CardMedia,
  CardContent,
  CardActions,
  Avatar,
  IconButton,
  Button,
} from '@material-ui/core';
import FavoriteIcon from '@material-ui/icons/Favorite';
import ShareIcon from '@material-ui/icons/Share';
import MoreVertIcon from '@material-ui/icons/MoreVert';
import { useHistory } from 'react-router-dom';
import moment from 'moment';
import Markdown from './Markdown';

const useStyles = makeStyles((theme) => ({
  root: {
    width: '100%',
    marginBottom: theme.spacing(3),
  },
  media: {
    height: 0,
    paddingTop: '56.25%', // 16:9
  },
  look: {
    transform: 'rotate(0deg)',
    marginLeft: 'auto',
    transition: theme.transitions.create('transform', {
      duration: theme.transitions.duration.shortest,
    }),
  },
  expandOpen: {
    transform: 'rotate(180deg)',
  },
  avatar: {},
  markdown: {
    ...theme.typography.body2,
    padding: theme.spacing(3, 0),
  },
}));

export default function ArticleCard(props) {
  const { post } = props;
  const classes = useStyles();
  const history = useHistory();

  const renderPreviewPost = (content) => {
    if (content) {
      const _content = content;
      if (_content.length > 200) {
        const slice200 = _content.slice(0, 200);
        const index = slice200.lastIndexOf('\n');
        if (index > -1) {
          return `${slice200}...`;
        }
        return slice200.slice(0, index);
      }
      return content;
    }
    return '';
  };

  const handleLookArticle = (id) => {
    history.push(`/article/${id}`);
  };

  return (
    <Card className={classes.root}>
      <CardHeader
        avatar={(
          <Avatar className={classes.avatar}>
            {post.userInfo.name && post.userInfo.name.slice(0, 1)}
          </Avatar>
        )}
        action={(
          <IconButton aria-label="settings">
            <MoreVertIcon />
          </IconButton>
        )}
        title={post.userInfo.name}
        subheader={moment(post.time).format('YYYY-MM-DD HH:mm')}
      />
      {post.banner && (
        <CardMedia className={classes.media} image={post.banner} />
      )}
      <CardContent>
        <Markdown className={classes.markdown}>
          {renderPreviewPost(post.post)}
        </Markdown>
      </CardContent>
      <CardActions disableSpacing>
        <IconButton aria-label="add to favorites">
          <FavoriteIcon />
        </IconButton>
        <IconButton aria-label="share">
          <ShareIcon />
        </IconButton>
        <Button
          className={classes.look}
          size="small"
          color="primary"
          onClick={() => {
            handleLookArticle(post._id);
          }}
        >
          查看原文
        </Button>
      </CardActions>
    </Card>
  );
}
